package com.tuliyou.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.tuliyou.common.util.Result;
import com.tuliyou.dto.MajorDTO;
import com.tuliyou.dto.PageInfo;
import com.tuliyou.entity.Major;
import com.tuliyou.mapper.MajorMapper;
import com.tuliyou.service.MajorService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class MajorServiceImpl extends ServiceImpl<MajorMapper, Major> implements MajorService {

    @Resource
    private MajorMapper majorMapper;

    @Override
    public Result<PageInfo<MajorDTO>> getMajors(Integer page, Integer size, String majorName, String parentCode, String level, String degreeType, String years) {
        // 设置分页参数
        PageHelper.startPage(page, size);
        // 执行查询
        List<Major> majorList = majorMapper.getMajors(majorName,parentCode,level,degreeType,years);
        // 关键：先将查询结果强转为Page<Major>，保留分页信息
        Page<Major> majorPage = (Page<Major>) majorList;
        // 转换DTO：基于原始Page的list进行stream映射（不破坏分页信息）
        List<MajorDTO> majorDTOList = majorPage.stream().map(MajorDTO::fromMajor).toList();
        // 封装PageInfo对象
        PageInfo<MajorDTO> pageInfo = new PageInfo<>();
        pageInfo.setCurrent(majorPage.getPageNum()); // 当前页码
        pageInfo.setSize(majorPage.getPageSize()); // 每页条数
        pageInfo.setTotal(majorPage.getTotal()); // 总记录数
        pageInfo.setPages(majorPage.getPages()); // 总页数
        pageInfo.setRecords(majorDTOList); // 当前页DTO列表
        return Result.success(pageInfo);
    }

    @Override
    public Result<MajorDTO> getMajorDetail(String majorCode) {
        Major major = majorMapper.getMajorDetail(majorCode);
        MajorDTO majorDTO = MajorDTO.fromMajor(major);
        return Result.success(majorDTO);
    }
}
